package com.tianze.library.base;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.tianze.library.R;
import com.tianze.library.adapter.recycler.RecyclerBaseAdapter;
import com.tianze.library.utils.NetUtils;
import com.tianze.library.view.EmptyLayout;

import java.util.List;

import butterknife.ButterKnife;

/**
 * Created by kingtami.
 */
public abstract class BaseRefreshFragment extends BaseFragment implements RecyclerBaseAdapter.OnItemClickListener, RecyclerBaseAdapter.OnItemLongClickListener {

    protected static final int STATE_NONE = 0;
    protected static final int STATE_REFRESH = 1;
    protected static final int STATE_LOADMORE = 2;
    protected int mState = STATE_NONE;

    protected static final int DEFAULT_PAGE = 1;
    protected int preloadSize = 4;
    protected int mCurrentPage = 1;
    protected int pageSize = 10;

    protected int mStoreEmptyState = -1;
    protected String mStoreEmptyMessage;

    protected RecyclerView mRecyclerView;
    protected EmptyLayout mErrorLayout;
    protected LinearLayoutManager mLayoutManager;
    protected RecyclerBaseAdapter mAdapter;

    protected RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            int totalItemCount = mLayoutManager.getItemCount();
            if (canLoadMore() && lastVisibleItem >= totalItemCount - preloadSize && dy > 0) {
                if (mState == STATE_NONE && mAdapter != null && mAdapter.getDataSize() > 0) {
                    loadMore();
                }
            }
        }
    };

    @Override
    protected void initData() {
    }

    @Override
    protected void initView() {
        beforeInitView();
        mLayoutManager = getLayoutManager();
        mRecyclerView = ButterKnife.findById(rootView, R.id.recycler_view);
        mErrorLayout = ButterKnife.findById(rootView, R.id.error_layout);
        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                refresh();
            }
        });

        mRecyclerView.setOnScrollListener(mScrollListener);

        if (isNeedListDivider()) {
            mRecyclerView.addItemDecoration(
                    new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        }
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        if (mAdapter != null) {
            mRecyclerView.setAdapter(mAdapter);
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        } else {
            mAdapter = getListAdapter();
            mAdapter.setOnItemClickListener(this);
            mAdapter.setOnItemLongClickListener(this);
            mRecyclerView.setAdapter(mAdapter);
            if (requestDataIfViewCreated()) {
                refresh();
            } else {
                mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            }
        }

        if (mStoreEmptyState != -1) {
            mErrorLayout.setErrorType(mStoreEmptyState);
        }
        if (!TextUtils.isEmpty(mStoreEmptyMessage)) {
            mErrorLayout.setErrorMessage(mStoreEmptyMessage);
        }
    }

    protected abstract void beforeInitView();

    protected LinearLayoutManager getLayoutManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return layoutManager;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mErrorLayout) {
            mStoreEmptyState = mErrorLayout.getErrorState();
            mStoreEmptyMessage = mErrorLayout.getMessage();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onItemClick(View view) {
        onItemClick(view, mRecyclerView.getChildPosition(view));
    }

    protected void onItemClick(View view, int position) {
    }

    @Override
    public boolean onItemLongClick(View view) {
        return onItemLongClick(view, mRecyclerView.getChildPosition(view));
    }

    protected boolean onItemLongClick(View view, int position) {
        return false;
    }

    protected abstract RecyclerBaseAdapter getListAdapter();

    protected boolean requestDataIfViewCreated() {
        return true;
    }

    protected void notifyDataSetChanged() {
        if (mAdapter != null)
            mAdapter.notifyDataSetChanged();
    }

    protected void onRequestError() {
        if (mCurrentPage == 1) {
            String message = "网络异常,请检查后再试";
            if (mAdapter.getDataSize() == 0) {
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            } else {
                mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                if (NetUtils.isConnected(mActivity.getApplicationContext())) {
                    message = getString(R.string.tip_load_data_error);
                } else {
                    message = getString(R.string.tip_network_error);
                }
            }
            toast(message);
        } else {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            mAdapter.setState(RecyclerBaseAdapter.STATE_NETWORK_ERROR);
        }
        mAdapter.notifyDataSetChanged();
    }

    protected void onRequestFinish() {
        mState = STATE_NONE;
    }

    protected void onRequestResponse(List infoList) {
        if (mState == STATE_REFRESH)
            mAdapter.clear();
        if (null == infoList) {
            mErrorLayout.setErrorType(EmptyLayout.NODATA);
            return;
        }
        mAdapter.addData(infoList);
        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        if (infoList.size() == 0 && mState == STATE_REFRESH) {
            mErrorLayout.setErrorType(EmptyLayout.NODATA);
        } else if (infoList.size() < pageSize) {
            if (mState == STATE_REFRESH)
                mAdapter.setState(RecyclerBaseAdapter.STATE_LESS_ONE_PAGE);
            else
                mAdapter.setState(RecyclerBaseAdapter.STATE_NO_MORE);
        } else {
            mAdapter.setState(RecyclerBaseAdapter.STATE_LOAD_MORE);
        }
    }

    public void refresh() {
        mCurrentPage = DEFAULT_PAGE;
        mState = STATE_REFRESH;
        // mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        // 如果设置HIDE_LAYOUT,刷新的时候不显示加载
        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        requestData(true);
    }

    public void loadMore() {
        if (mState == STATE_NONE) {
            if (mAdapter.getState() == RecyclerBaseAdapter.STATE_LOAD_MORE) {
                mCurrentPage++;
                mState = STATE_LOADMORE;
                requestData(false);
            }
        }
    }

    protected void requestData(boolean refresh) {
        sendRequestData();
    }

    protected void sendRequestData() {
    }

    protected boolean isNeedListDivider() {
        return true;
    }

    protected boolean canLoadMore() {
        return true;
    }
//    protected Context mContext(){
//        return mActivity;
//    }
}
